import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { staticRoutes } from "@/router/routes";
import { reqGetUserInfo, reqLogin, reqLogout } from "@/api/user";

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: "",
      avatar: "",
    },
    menuRoutes: staticRoutes,
  }),

  actions: {
    // 登录请求
    async login(username: string, password: string) {
      const result = await reqLogin(username, password);
      console.log(result);
      // 将token 存到pinia中
      this.token = result.token;
      // 将token持久化保存
      setToken(result.token);
    },
    // 获取用户信息
    async getInfo() {
      const result = await reqGetUserInfo();
      // console.log(result);
      this.userInfo = result;
    },
    // 退出登录
    async logout() {
      // 发送退出请求  远程失效token
      await reqLogout();
      // 清除浏览器中的token 和用户信息
      this.reset();
    },

    reset() {
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.userInfo = {
        routes: [],
        buttons: [],
        roles: [],
        name: "",
        avatar: "",
      };
    },
  },
});
